package WebSocket;

import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

import org.springframework.stereotype.Component;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

@Component
@ChannelHandler.Sharable
public class Handler extends ChannelInboundHandlerAdapter {
	private static final InternalLogger logger = InternalLoggerFactory.getInstance(Handler.class);

	private Context context = ZMQ.context(1);
	private Socket socket = context.socket(ZMQ.PUSH);

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		socket.connect("tcp://*:38346");
		ctxList.add(ctx);
		System.out.println("channelActive");
	}

	public static ArrayBlockingQueue<String> msg = new ArrayBlockingQueue<String>(1024);

	// 一共有6种，目前只判断2种

	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof TextWebSocketFrame) {
			String text = ((TextWebSocketFrame) msg).text();
			System.out.println(text);

			ReferenceCountUtil.release(msg);
		} else if (msg instanceof BinaryWebSocketFrame) {
			ReferenceCountUtil.release(msg);
		} else if (msg instanceof WebSocketFrame) {
			ReferenceCountUtil.release(msg);
		} else {
			ReferenceCountUtil.release(msg);
		}

	}

	private HashMap<String, String> tableCardsSMap = new HashMap<String, String>();

	private void process(byte[] bytes) {

	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
//		System.out.println("channelUnregistered");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		ctxList.remove(ctx);
//		System.out.println("channelInactive,remove id");
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
			ctx.pipeline().remove(WebSocketServerProtocolHandler.class);
		}
		if (evt instanceof IdleStateEvent) {
			// 服务端对应着读事件，当为READER_IDLE时触发
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.READER_IDLE) {
				logger.info("rec timeout,close");
			} else {
				super.userEventTriggered(ctx, evt);
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}

	}

	private static List<ChannelHandlerContext> ctxList = new ArrayList<ChannelHandlerContext>();

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("channel Registered");

	}

	public static void sendMessage(String s) {
		for (ChannelHandlerContext ctx : ctxList) {
			
			
//			System.out.println(s);
			ctx.channel().writeAndFlush(new TextWebSocketFrame(s));
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

}
